package pers.cz.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.cz.config.JefConfiguration;
import pers.cz.netty.config.ServerNettyConfigItem;
import pers.cz.netty.handle.ServerHeartBeatHandler;
import pers.cz.netty.handle.ServerIdleStateHandler;
import pers.cz.netty.handle.ServerMessageHandler;
import pers.cz.netty.protocal.TcpMessageDecoder;
import pers.cz.netty.protocal.TcpMessageEncoder;
import pers.cz.netty.protocal.ProtocalConst;

/**
 * @program: PostGirl-panent
 * @description: 服务端
 * @author: Cheng Zhi
 * @create: 2022-10-05 08:08
 **/
public class TcpNettyServer {

    private static final Logger log = LoggerFactory.getLogger(TcpNettyServer.class);

    private int port;

    public TcpNettyServer(int port) {
        this.port = port;
    }

    public void start(ServerMessageHandler serverMessageHandler) {
        //LogUtil.initLog();

        showBanner();
        // 负责连接
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 负责除连接之外的工作
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)

                    //实例化ServerSocketChannel
                    .channel(NioServerSocketChannel.class)

                    //设置ServerSocketChannel的TCP参数
                    .option(ChannelOption.SO_BACKLOG, 1024)

                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // http服务端编解码规则
                            ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(JefConfiguration.getInt(ServerNettyConfigItem.SERVER_HEART_READ_TIME, 15), 0, 0));
                            ch.pipeline().addLast("ServerIdleStateHandler", new ServerIdleStateHandler());
                            // 长度解码：包最大值 数据内容偏移量
                            //ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(ProtocalConst.PACKAGE_MAX_SIZE,9,8,0,0));
                            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(ProtocalConst.PACKAGE_MAX_SIZE,0,8,0,8));
                            ch.pipeline().addLast(new LengthFieldPrepender(8));
                            //ch.pipeline().addLast(new AutoLengthFieldDecoder(ProtocalConst.PACKAGE_MAX_SIZE,9,8,0,0));
                            //ByteBuf delimiter = Unpooled.copiedBuffer("$POSTGIRL$".getBytes());
                            //ch.pipeline().addLast(new DelimiterBasedFrameDecoder(ProtocalConst.PACKAGE_MAX_SIZE, delimiter));
                            ch.pipeline().addLast(new TcpMessageEncoder());
                            ch.pipeline().addLast(new TcpMessageDecoder());
                            ch.pipeline().addLast(new ServerHeartBeatHandler());
                            ch.pipeline().addLast(serverMessageHandler);

                        }
                    });
            //绑定监听端口，调用sync同步阻塞方法等待绑定操作完
            ChannelFuture future = b.bind(this.port).sync();
            final boolean success = future.isSuccess();
            log.debug("netty service has been started, listen on: {} port", this.port);
            //成功绑定到端口之后,给channel增加一个管道关闭的监听器并同步阻塞,直到channel关闭,线程才会往下执行,结束进程。
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("netty service failed to start on " + port + " port", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public void showBanner() {
        log.info("================================================================================");
        log.info("==     ~~~   jef TCP netty server is starting    ~~~                         ==");
        log.info("================================================================================");
    }
/*    public static void main(String[] args) {
        new NettyServer(8881).start(null);
    }*/
}
